// 用户信息相关
import {
    SET_MEMBER_INFO,
    SET_MEMBER_ID,
    GET_MEMBER_CARD_STORES_INFO,
    SET_MEMBER_CARD_BALANCE_LOG,
    SET_MEMBER_CARD_INTEGRAL_LOG,
    GET_MEMBER_CARD_RECHARGE_STATE,
    SET_MEMBER_SHOW_CARD,
    GET_RECHARGE_ACTIVITY,
    GET_MEMBER_COUPONS,
    GET_ENTITY_CARD_INFO,
    SET_SELECT_CARD_INFO,
    GET_MEMBER_COUPONS_STORES_INFO,
    GET_MEMBER_COUPONS_PRODUCT_INFO,
    SET_RECHARGE_MEMBER_CARD,
    SET_MEMBER_INDEX_RECHARGE_CARD,
    GET_ACTIVITY_INFO,
    GET_BRAND_OR_PUBLIC_INFO,
    GET_INTEGRAL_SHOP_LIST,
    SET_BUSINESS_TYPE_VALUE,
} from '@store/mutationType';

import logger from '@common/logger';
// market
import {
    updateMemberInfo,
    changeNoPwdStatus,
    setPassword,
    getAccountLog,
    getCardIntegralLog,
    getRechargeActivity,
    getMemberCouponList,
    getEntityCard,
    getMemberCardByStoreId,
    getCouponsActivity,
    joinCouponsActivity,
    getIntegralShopData,
    integralExchangeCoupon,
    getMemberInfoNew,
} from '@common/market';
import { TipSuccess, TipError } from '@common/tip';
import { get, post } from '@common/ajax';
import { getShowCard, dealIntegralShopData } from '@biztools/member';
import { setUserTokenCookie, setUserMemberIdCookie, getUserMemberIdCookie, getUserTokenCookie } from '@biztools/info';
import urls from '@common/url';
import { MEMBER_BIZ_TYPE } from '@constants/member';

const member = {
    state: {
        memberId: getUserMemberIdCookie(),
        memberInfo: {},
        memberCardStoresInfo: [],
        memberCardBalanceLog: [],
        memberCardIntegralLog: [],
        memberShowCardInfo: null,
        rechargeActivity: [],
        rechargeMemberCard: {},
        memberCoupons: [],
        memberCouponsStoresInfo: [],
        memberCouponsProductsInfo: [],
        entityCardInfo: null,
        selectCardInfo: null,
        memberIndexRechargeCard: null,
        activityInfo: {},
        brandOrPublicInfo: {},
        integralShopList: [],
        memberCardRechargeState: [],
        memberBusinessType: MEMBER_BIZ_TYPE.all, // 业务类型
    },
    mutations: {
        SET_MEMBER_ID: (state, memberId) => {
            Object.assign(state, {
                memberId,
            });
        },
        SET_MEMBER_INFO: (state, memberInfo) => {
            Object.assign(state, {
                memberInfo,
            });
        },
        GET_MEMBER_CARD_STORES_INFO: (state, memberCardStoresInfo) => {
            Object.assign(state, {
                memberCardStoresInfo,
            });
        },
        SET_MEMBER_CARD_BALANCE_LOG: (state, memberCardBalanceLog) => {
            Object.assign(state, {
                memberCardBalanceLog,
            });
        },
        SET_MEMBER_CARD_INTEGRAL_LOG: (state, memberCardIntegralLog) => {
            Object.assign(state, {
                memberCardIntegralLog,
            });
        },
        SET_MEMBER_SHOW_CARD: (state, memberShowCardInfo) => {
            Object.assign(state, {
                memberShowCardInfo,
            });
        },
        GET_RECHARGE_ACTIVITY: (state, rechargeActivity) => {
            // 升序排列充值活动
            Object.assign(state, {
                rechargeActivity: rechargeActivity.sort((a, b) => a.quota - b.quota),
            });
        },
        GET_MEMBER_COUPONS: (state, memberCoupons) => {
            Object.assign(state, {
                memberCoupons,
            });
        },
        GET_ENTITY_CARD_INFO: (state, entityCardInfo) => {
            Object.assign(state, {
                entityCardInfo,
            });
        },
        SET_SELECT_CARD_INFO: (state, selectCardInfo) => {
            Object.assign(state, {
                selectCardInfo,
            });
        },
        GET_MEMBER_COUPONS_STORES_INFO: (state, memberCouponsStoresInfo) => {
            Object.assign(state, {
                memberCouponsStoresInfo,
            });
        },
        GET_MEMBER_COUPONS_PRODUCT_INFO: (state, memberCouponsProductsInfo) => {
            Object.assign(state, {
                memberCouponsProductsInfo,
            });
        },
        SET_RECHARGE_MEMBER_CARD: (state, rechargeMemberCard) => {
            Object.assign(state, {
                rechargeMemberCard,
            });
        },
        SET_MEMBER_INDEX_RECHARGE_CARD: (state, memberIndexRechargeCard) => {
            Object.assign(state, {
                memberIndexRechargeCard,
            });
        },
        GET_ACTIVITY_INFO: (state, activityInfo) => {
            Object.assign(state, {
                activityInfo,
            });
        },
        GET_BRAND_OR_PUBLIC_INFO: (state, brandOrPublicInfo) => {
            Object.assign(state, {
                brandOrPublicInfo,
            });
        },
        GET_INTEGRAL_SHOP_LIST: (state, integralShopList) => {
            Object.assign(state, {
                integralShopList,
            });
        },
        GET_MEMBER_CARD_RECHARGE_STATE: (state, memberCardRechargeState) => {
            Object.assign(state, {
                memberCardRechargeState,
            });
        },
        SET_BUSINESS_TYPE_VALUE: (state, memberBusinessType) => {
            Object.assign(state, { memberBusinessType });
        },
    },
    actions: {
        // 设置会员id
        setMemberId: ({ commit }, memberId) => {
            commit(SET_MEMBER_ID, memberId);
        },
        // 更新会员id
        updateMemberId: ({ dispatch }, res) => {
            const { member_id, token } = res;
            // 重新设置token，memberId的cookie
            setUserTokenCookie(token);
            setUserMemberIdCookie(member_id);
            // 更新用户信息
            dispatch('refreshMemberInfo');
        },
        // 获取会员信息
        getMemberInfo: async ({ dispatch, state, commit }, type) => {
            logger.warn('Member => 获取会员信息：', type);
            // const { memberBusinessType } = state;
            const memberInfo = await getMemberInfoNew(getUserTokenCookie(), type || MEMBER_BIZ_TYPE.shop);
            logger.info('会员信息：', memberInfo);
            dispatch('setMemberInfo', { ...memberInfo, token: getUserTokenCookie() });
            commit(SET_BUSINESS_TYPE_VALUE, type || MEMBER_BIZ_TYPE.shop);
        },
        // 设置会员信息
        setMemberInfo: ({ commit, dispatch }, memberInfo) => {
            commit(SET_RECHARGE_MEMBER_CARD, memberInfo.groups[0]);
            commit(SET_MEMBER_INFO, memberInfo);
            memberInfo.token && setUserTokenCookie(memberInfo.token);
            dispatch('setMemberShowCardInfo');
            dispatch('queryGroupsRechargeState');
        },
        // 设置会员首页展示卡信息
        setMemberShowCardInfo: ({ commit, state, dispatch }) => {
            let showCard = getShowCard(state.memberInfo.groups, '');
            logger.info('获取到的会员展示卡为：', showCard);
            logger.warn('当前选中的卡为：', state.selectCardInfo);
            if (state.selectCardInfo) {
                showCard = state.memberInfo.groups.filter(item => `${item.groupId}` === `${state.selectCardInfo.groupId}`)[0];
                dispatch('setSelectCardInfo', showCard);
            }
            if (showCard) {
                commit(SET_MEMBER_SHOW_CARD, showCard);
                commit(SET_RECHARGE_MEMBER_CARD, showCard);
                commit(SET_MEMBER_INDEX_RECHARGE_CARD, showCard);
                // dispatch('getRechargeActivityList', showCard.groupId);
            }
        },
        setRechargeMemberCard: ({ commit, state, dispatch }, cardId) => {
            const { groups } = state.memberInfo;
            const cardInfo = (groups || []).filter(item => `${item.gradeId}` === `${cardId}`)[0];
            commit(SET_RECHARGE_MEMBER_CARD, cardInfo);
            dispatch('getRechargeActivityList', cardInfo.groupId);
        },
        // 更新用户信息
        updateMemberBaseInfo: async ({ dispatch }, { code, authInfo }) => {
            const res = await post(urls.updateMember, {
                code,
                'auth_appid': authInfo.auth_appid,
                'component_appid': authInfo.component_appid,
            });
            if (res) {
                dispatch('refreshMemberInfo');
                return true;
            }
            return false;
        },
        // 更新手机号
        updateMemberMobile: async ({ dispatch, state }, mobile) => {
            const res = await updateMemberInfo(state.memberInfo.token, {
                mobile,
            });
            if (res) {
                dispatch('refreshMemberInfo');
            } else {
                logger.error('更新会员手机号失败', res);
            }
            return res;
        },
        // 更新性别
        updateMemberSex: async ({ dispatch, state }, sex) => {
            const res = await updateMemberInfo(state.memberInfo.token, {
                sex,
            });
            if (res) {
                TipSuccess('更新性别成功');
                dispatch('refreshMemberInfo');
            } else {
                logger.error('更新会员性别失败', res);
            }
            return res;
        },
        // 更新生日
        updateMemberBirthday: async ({ dispatch, state }, birthday) => {
            const res = await updateMemberInfo(state.memberInfo.token, {
                birthday,
            });
            if (res) {
                TipSuccess('更新生日成功');
                dispatch('refreshMemberInfo');
            } else {
                logger.error('更新会员生日失败', res);
            }
            return res;
        },
        // 开通免密支付
        openNoPasswordPay: async ({ dispatch, state }) => {
            const res = await changeNoPwdStatus(state.memberInfo.token, true);
            if (res) {
                TipSuccess('开通成功！');
                dispatch('refreshMemberInfo');
                return true;
            } else {
                TipError('开通失败！');
                return false;
            }
        },
        // 关闭免密支付
        closeNoPasswordPay: async ({ dispatch, state }) => {
            const res = await changeNoPwdStatus(state.memberInfo.token, false);
            if (res) {
                TipSuccess('关闭成功！');
                dispatch('refreshMemberInfo');
                return true;
            } else {
                TipError('关闭失败！');
                return false;
            }
        },
        // 设置会员密码&修改密码
        setMemberPassword: async ({ dispatch, state }, password) => {
            const flag = await setPassword(state.memberInfo.token, password);
            if (flag) {
                TipSuccess('设置密码成功');
                dispatch('refreshMemberInfo');
            } else {
                TipError('设置密码失败，请重试');
            }
        },
        // 更新会员信息
        refreshMemberInfo: async ({ commit, state, dispatch }) => {
            const memberInfo = await getMemberInfoNew(getUserTokenCookie(), state.memberBusinessType || MEMBER_BIZ_TYPE.shop);
            logger.info('更新用户信息', memberInfo);
            dispatch('setMemberInfo', { ...memberInfo, token: getUserTokenCookie() });
        },
        // 会员绑定手机号
        memberBindPhone: async ({ dispatch }, { mobile, code }) => {
            logger.info('传入的参数', mobile, code);
            const res = await post(urls.bindPhone, {
                mobile,
                code,
            });
            if (res) {
                // 绑定成功，涉及合并逻辑，重新更新用户的信息
                dispatch('updateMemberId', res);
                // 补偿刷新会员信息
                dispatch('refreshMemberInfo');
                TipSuccess('手机号绑定成功');
                return true;
            } else {
                TipSuccess('手机号绑定失败');
                return false;
            }
        },
        // 根据id获取门店基础信息
        getStoreInfoByIds: async ({ commit }, storeIds=[]) => {
            const res = await get(urls.availableStore, {
                ids: storeIds.join(','),
            });
            commit(GET_MEMBER_CARD_STORES_INFO, res.stores);
        },
        // 根据id获取门店基础信息
        getCouponsStoreInfoByIds: async ({ commit }, storeIds=[]) => {
            const res = await get(urls.availableStore, {
                ids: storeIds.join(','),
            });
            commit(GET_MEMBER_COUPONS_STORES_INFO, res.stores);
            return res.stores;
        },
        // 根据菜品ids和菜谱ids获取相应的菜品名称
        getCouponsProductsInfoByIds: async ({ commit }, { productIds, menuIds, standards }) => {
            const res = await get(urls.availableProduct, {
                ids: productIds.join(','),
                menu_ids: menuIds.join(','),
                standard_refs: standards.join(','),
            });
            commit(GET_MEMBER_COUPONS_PRODUCT_INFO, res.products);
        },
        // 分页获取卡金额变动记录
        getCardBalanceRecordByPage: async ({ commit, state }, { groupId, page, clear=false }) => {
            const res = await getAccountLog(state.memberInfo.id, groupId, page);
            logger.success('获取到的变动记录为：', res);
            const arrs = clear ? res.list : state.memberCardBalanceLog.concat(res.list);
            commit(SET_MEMBER_CARD_BALANCE_LOG, arrs);
        },
        // 分页获取卡积分变动记录
        getCardIntegralRecordByPage: async ({ commit, state }, { groupId, page, clear=false }) => {
            const res = await getCardIntegralLog(state.memberInfo.id, groupId, page);
            logger.success('获取到的变动记录为：', res);
            const arrs = clear ? res : state.memberCardIntegralLog.concat(res.list);
            commit(SET_MEMBER_CARD_INTEGRAL_LOG, arrs);
        },
        // 获取充值活动梯度
        getRechargeActivityList: async ({ commit }, groupId) => {
            const res = await getRechargeActivity(groupId);
            logger.success('获取的优惠活动：', res, groupId);
            if (res) {
                commit(GET_RECHARGE_ACTIVITY, res);
            }
        },
        // 获取会员1个月内所有优惠券
        getMemberCoupons: async ({ commit, state }) => {
            const res = await getMemberCouponList(state.memberInfo.token);
            commit(GET_MEMBER_COUPONS, res);
        },
        // 根据卡号查询实体卡信息
        getEntityCardInfo: async ({ commit }, cardNum) => {
            const res = await getEntityCard(cardNum);
            logger.info('查询到的信息为：', res);
            commit(GET_ENTITY_CARD_INFO, res);
            return res;
        },
        // 线上会员绑定实体卡
        memberBindEntityCard: async ({ dispatch }, cardNum) => {
            const res = await post(urls.bindEntityCard, {
                uuid: cardNum,
                store_id: '',
            });
            const { member_id, token } = res;
            if (member_id && token) {
                // 设置用户token
                setUserTokenCookie(token);
                setUserMemberIdCookie(member_id);
                TipSuccess('绑定成功');
                // 绑定成功，涉及合并逻辑，重新更新用户的信息
                dispatch('updateMemberId', res);
                // 补偿刷新会员信息
                dispatch('refreshMemberInfo');
            } else {
                logger.error('绑定失败');
            }
        },
        // 设置选中使用的会员卡
        setSelectCardInfo: ({ commit, dispatch }, cardInfo) => {
            commit(SET_SELECT_CARD_INFO, cardInfo);
            if (cardInfo) {
                dispatch('getRechargeActivityList', cardInfo.groupId);
            }
        },
        // 设置会员中心首页充值卡
        setMemberIndexRechargeCard: ({ commit, dispatch }, cardInfo) => {
            commit(SET_MEMBER_INDEX_RECHARGE_CARD, cardInfo);
            dispatch('getRechargeActivityList', cardInfo.groupId);
        },
        // 获取用户参加的活动，通过活动id
        getActivityInfo: async ({ commit, state }, activityId) => {
            logger.info('获取会员参与的活动信息');
            const { token } = state.memberInfo;
            if (token) {
                const res = await getCouponsActivity(token, activityId);
                logger.info('获取到的活动信息', res);
                commit(GET_ACTIVITY_INFO, res);
            }
        },
        // 用户参加活动
        joinAtivity: async ({ dispatch, state } , activityId) => {
            logger.info('用户开始参与活动，活动id：', activityId);
            const { token } = state.memberInfo;
            if (token) {
                const res = await joinCouponsActivity(token, activityId);
                if (res) {
                    dispatch('refreshMemberInfo');
                    return true;
                } else {
                    return false;
                }
            }
        },
        // 获取显示的主体信息
        getBrandOrPublicInfo: async ({ commit }) => {
            const res = await get(urls.brandOrPublicInfo);
            if (res) {
                commit(GET_BRAND_OR_PUBLIC_INFO, res);
            }
        },
        // 获取积分商城数据
        getIntegralShopList: async ({ commit }, { groupId, cardTypeId }) => {
            const res = await getIntegralShopData({ groupId, cardTypeId });
            logger.success('获取到的积分商城数据为：', res);
            logger.success('处理后的数据为：', dealIntegralShopData(res));
            if (res) {
                commit(GET_INTEGRAL_SHOP_LIST, dealIntegralShopData(res));
            }
        },
        exchangeCoupon: async ({ state, dispatch }, { cardInfo, activityId }) => {
            const { memberInfo } = state;
            const flag = await integralExchangeCoupon(memberInfo.token, {
                groupId: cardInfo.groupId,
                cardTypeId: cardInfo.gradeId,
                activityId,
                memberId: memberInfo.id,
            });
            if (flag) {
                TipSuccess('兑换成功');
                dispatch('refreshMemberInfo');
            } else {
                // TipError('兑换失败');
            }
        },
        // 查询会员卡是否支持充值
        queryGroupsRechargeState: async ({ state, commit }) => {
            const { memberInfo } = state;
            const groupArray = memberInfo.groups.map(item => item.groupId);
            if (groupArray && groupArray.length > 0) {
                const res = await get(urls.searchRechargeState, {
                    group_ids: groupArray.join(','),
                });
                commit(GET_MEMBER_CARD_RECHARGE_STATE, res.groups || []);
            }
        },
    },
};

export default member;
